package com.example.newsapp.activity;


import static com.example.newsapp.constant.NetConstant.BASE_URL;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.newsapp.R;
import com.example.newsapp.adapter.NewsAdapter;
import com.example.newsapp.model.NewsItem;
import com.example.newsapp.model.Result;
import com.example.newsapp.utils.HttpUtil;
import com.example.newsapp.utils.UserSessionUtil;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class LovedActivity extends AppCompatActivity {

    private RecyclerView LovedRecyclerView;
    private NewsAdapter adapter;
    private List<NewsItem> lovedList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loved);

        findViewById(R.id.btnBack).setOnClickListener(v -> finish());
        LovedRecyclerView = findViewById(R.id.LovedRecyclerView);
        LovedRecyclerView.setLayoutManager(new LinearLayoutManager(this));

        if (!UserSessionUtil.isLoggedIn(LovedActivity.this)){
            Toast.makeText(this, "登录已过期，请重新登录", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
        }

        requestMyLovedNews();
    }

    private void requestMyLovedNews() {
        String requestUrl = BASE_URL + "/users/loved" ;
        Type resultType = new TypeToken<Result<List<NewsItem>>>() {
        }.getType();
        HttpUtil.request(LovedActivity.this,requestUrl, "GET", null, resultType, new HttpUtil.Callback<Result<List<NewsItem>>>() {
            @Override
            public void onSuccess(Result<List<NewsItem>> result) {
                handleNewsItemResponse(result);
            }

            @Override
            public void onFailure(Exception e) {
                showToast("查询出错");
            }
        });
    }

    private void handleNewsItemResponse(Result<List<NewsItem>> response) {
        if (response == null) {
            showToast("服务器响应异常");
            return;
        }

        if (response.getCode() == 1 && response.getData() != null) {
            lovedList = response.getData();
            // 2. 设置适配器
            adapter = new NewsAdapter(lovedList);
            LovedRecyclerView.setAdapter(adapter);
        } else {
            String errorMsg = response.getMsg();
            if (errorMsg == null || errorMsg.isEmpty()) errorMsg = "未知错误";
            showToast("获取+" + "喜欢列表失败：" + errorMsg);
        }
    }
    private void showToast(String msg) {
        Toast.makeText(LovedActivity.this, msg, Toast.LENGTH_SHORT).show();
    }

}
